package com.jblog.core.service.account.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jblog.core.CoreUtil;
import com.jblog.core.dao.account.AccountDao;
import com.jblog.core.model.account.Account;
import com.jblog.core.model.account.param.AccountParam;
import com.jblog.core.service.account.AccountService;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired private AccountDao accountDao;
    
    @Override
    public Account login(Account e) {
        return findByName(e.getName());
    }

    @Override
    public Long count(AccountParam p) {
        return accountDao.count(p);
    }

    @Override
    public void delete(Long id) {
        accountDao.deleteByPk(id);
    }

    @Override
    public void enDisable(Account e, boolean able) {
        if (!CoreUtil.checkStatus(e.getStatus(), able)) {
            update(new Account(e.getId(), CoreUtil.toStatus(able)));
        }
    }

    @Override
    public Account findByName(String s) {
        return findOne(new AccountParam(s));
    }

    @Override
    public Account findById(Long id) {
        return findOne(new AccountParam(id));
    }

    @Override
    public Account findByEmail(String s) {
        AccountParam param = new AccountParam();
        param.setEmail(s);
        return findOne(param);
    }

    @Override
    public Account findByActiveCode(String s) {
        AccountParam param = new AccountParam();
        param.setActiveCode(s);
        return findOne(param);
    }

    @Override
    public List<Account> findByParam(AccountParam p) {
        return accountDao.byParam(p);
    }

    @Override
    public void save(Account e) {
        accountDao.save(e);
    }

    @Override
    public void update(Account e) {
        accountDao.update(e);
    }

    private Account findOne(AccountParam p) {
        List<Account> es = findByParam(p);
        if (null != es && es.size() == 1) {
            return es.get(0);
        } 
        return null;
    }
}
